package com.javabi.sizeof.definition;

import java.io.PrintStream;
import java.util.Set;

import com.javabi.sizeof.ClassDefinition;
import com.javabi.sizeof.ClassDefinitionMap;
import com.javabi.sizeof.MemoryUtil;

/**
 * A Boolean Array Definition.
 */
public final class ObjectArrayDefinition extends ClassDefinition<Object[]> {

	@Override
	public long sizeOf(Object[] array) {
		return sizeOfIntArray(array.length);
	}

	@Override
	public final boolean hasElements(Object[] array) {
		return array.length > 0;
	}

	@Override
	public long sizeOfElements(Object[] array, ClassDefinitionMap definitionMap, Set<Object> instanceSet, long size) {
		for (Object element : array) {
			if (element != null) {
				size += MemoryUtil.sizeOf(element, definitionMap, instanceSet);
			}
		}
		return size;
	}

	@Override
	public long sizeOfDebug(Object[] array, ClassDefinitionMap definitionMap, Set<Object> instanceSet, PrintStream stream) throws IllegalAccessException {
		long arraySize = sizeOfIntArray(array.length);
		stream.println("new Object[" + array.length + "] " + arraySize + " bytes");
		for (int index = 0; index < array.length; index++) {
			Object element = array[index];
			if (element != null) {
				long elementSize = MemoryUtil.sizeOfDebug(element, definitionMap, instanceSet, stream);
				stream.println("Object[" + index + "] " + elementSize + " bytes");
				arraySize += elementSize;
			}
		}
		return arraySize;
	}
}
